package com.zhiyou100.dao.impl;

import com.zhiyou100.dao.StudentDao;
import com.zhiyou100.entity.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.LogicalExpression;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.transaction.Transactional;
import java.util.List;

/**
 * 学生 dao 实现类
 *
 * @author yang
 * @version 1.0.0
 * @date 2020-09-24 22:52
 */
@Repository
public class StudentDaoImpl implements StudentDao {
    private SessionFactory factory;

    @Autowired
    public void setFactory(SessionFactory factory) {
        this.factory = factory;
    }

    private Session getSession() {
        return factory.openSession();
    }

    @Override
    public void addOne(Student o) {
        try (Session session = getSession()) {
            session.beginTransaction();
            session.save(o);
            session.getTransaction().commit();
        }
    }

    @Override
    public void deleteOne(Integer integer) {
        try (Session session = getSession()) {
            session.beginTransaction();
            session.delete(integer);
            session.getTransaction().commit();
        }
    }

    @Override
    public void updateOne(Student o) {
        try (Session session = getSession()) {
            session.beginTransaction();
            session.update(o);
            session.getTransaction().commit();
        }
    }

    @Override
    public List<Student> getAll() {

        try (Session session = getSession()) {
            return session.createCriteria(Student.class).list();
        }
    }

    @Override
    public Student getOne(Integer integer) {
        try (Session session = getSession()) {
            return session.get(Student.class, integer);
        }
    }

    @Override
    public Student selectOneByField(String field, Object value) {
        try (Session session = getSession()) {
            return (Student) session.createCriteria(Student.class).add(Restrictions.eq(field, value)).uniqueResult();
        }
    }


    @Override
    public Student selectOneByName(String name) {
        try (Session session = getSession()) {
            return (Student) session.createCriteria(Student.class).add(Restrictions.eq("id", name)).uniqueResult();
        }
    }

    @Override
    public Student selectOneByIdAndPwd(Integer id, String pwd) {
        try (Session session = getSession()) {
            final LogicalExpression and = Restrictions.and(Restrictions.eq("id", id), Restrictions.eq("password", pwd));
            return (Student) session.createCriteria(Student.class).add(and).uniqueResult();
        }
    }

}